package com.ym.jiujiangeyou;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import com.ym.jiujiangeyou.adapter.FoodListAdapter;
import com.ym.jiujiangeyou.app.AppManager;
import com.ym.jiujiangeyou.entity.Food;
import com.ym.jiujiangeyou.entity.Guide;
import com.ym.jiujiangeyou.entity.Hotel;
import com.ym.jiujiangeyou.entity.Scenery;
import com.ym.jiujiangeyou.parse.ParseGson;
import com.ym.jiujiangeyou.ui.DialogView;
import com.ym.jiujiangeyou.ui.XListView;
import com.ym.jiujiangeyou.ui.XListView.IXListViewListener;
import com.ym.jiujiangeyou.util.ConfigCache;
import com.ym.jiujiangeyou.util.Constants;
import com.ym.jiujiangeyou.util.HttpUtil;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

/**
 * @author 叶铭
 * @email yeming_1001@163.com
 * @version V1.0
 */
@SuppressLint("HandlerLeak")
public class FoodListActivity extends Activity implements IXListViewListener {

	private FoodListAdapter adapter;
	private XListView listView;
	private Dialog dialog;
	private Toast toast;
	private ProgressBar lv_foot_progress;
	private TextView lv_foot_more;
	private View lv_footer;
	private Handler handler;
	private Context context;
	private List<Food> nList, CList;
	private int status;
	private int count;
	TextView title_text;
	private LinearLayout title_back;
	private RelativeLayout rel_default_action ;
	private int defaul_action = Constants.LISTVIEW_ACTION_FIRST;
	private boolean isFirst = false;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		// 添加Activity到堆栈
		AppManager.getAppManager().addActivity(this);
		super.setContentView(R.layout.food_list);
		init();
		if (CList.isEmpty() || nList.isEmpty()) {
			loadData(Constants.LISTVIEW_ACTION_FIRST, handler, 1);
		}

	}

	public void init() {
		context = this;
		title_text = (TextView) findViewById(R.id.title_text);
		dialog = DialogView.popDialog(this, R.string.isloading);
		listView = (XListView) findViewById(R.id.foodlist);
		title_back = (LinearLayout) this.findViewById(R.id.title_back);
		rel_default_action = (RelativeLayout) this.findViewById(R.id.rel_default_action) ;
		adapter = new FoodListAdapter(context);
		nList = new ArrayList<Food>();
		CList = new ArrayList<Food>();
		listView.setPullLoadEnable(true);
		listView.setXListViewListener(this);

		title_text.setText(R.string.title_text_food_1);

		handler = new Handler() {
			@SuppressWarnings("unchecked")
			@Override
			public void handleMessage(Message msg) {
				// TODO Auto-generated method stub
				nList.clear();
				Map<String, Object> map;
				switch (msg.what) {
				case Constants.LISTVIEW_ACTION_FIRST:
					if(rel_default_action.getVisibility() == View.VISIBLE){
						rel_default_action.setVisibility(View.GONE) ;
						rel_default_action.setClickable(false) ;
					}
					map = (Map<String, Object>) msg.obj;
					nList = (List<Food>) map.get("food");
					CList.addAll(nList);
					adapter.setData(CList);
					count = CList.size();
					listView.setAdapter(adapter);
					dialog.dismiss();
					break;
				case Constants.LISTVIEW_ACTION_SCROLL:
				//	listView.nomore();
					//listView.stopLoadMore();
					map = (Map<String, Object>) msg.obj;
					int flag = (Integer) map.get("status");
					if (flag == 1) {
						nList = (List<Food>) map.get("food");;

					} else if (flag == 0) {
						listView.nomore();
					}
					listView.stopLoadMore();
					CList.addAll(nList);
					count = CList.size();
					adapter.setData(CList);
					break;
				case Constants.LISTVIEW_ACTION_GET_ERROR:
					dialog.dismiss();
					if(defaul_action == Constants.LISTVIEW_ACTION_FIRST){
						rel_default_action.setVisibility(View.VISIBLE) ;
						rel_default_action.setClickable(true) ;
					}
					toast = DialogView.popToast(context,
							R.string.http_connect_error);
					toast.show();
					break;
				}

				adapter.notifyDataSetChanged();
			}
		};

		listView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1,
					int position, long arg3) {
				// TODO Auto-generated method stub
				Food food = CList.get(position - 1);
				System.out.println("--------food.getFeature()--------"
						+ food.getFeature());
				Intent intent = new Intent(FoodListActivity.this,
						FoodDetails.class);
				Bundle bundle = new Bundle();
				bundle.putString("name", food.getName());
				bundle.putString("feature", food.getFeature());
				bundle.putString("introduct", food.getIntroduct());
				bundle.putString("url", food.getUrl());
				intent.putExtra("food", bundle);
				startActivity(intent);
			}
		});

		title_back.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				FoodListActivity.this.onBackPressed();
			}
		});
		
rel_default_action.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				loadData(Constants.LISTVIEW_ACTION_FIRST, handler, 1);
			}
		});
	}

	/**
	 * 
	 * @retur void
	 * @Description: 加载分页数据
	 */
	public void loadData(final int action, final Handler handler,
			final int pageNo) {

		if (action == Constants.LISTVIEW_ACTION_FIRST) {
			dialog.show();
		}

		new Thread(new Runnable() {

			Message message = new Message();
			Map<String, Object> map;
			String s;

			@Override
			public void run() {
				// TODO Auto-generated method stub
				switch (action) {
				case Constants.LISTVIEW_ACTION_FIRST:
				//	s = HttpUtil.httpGet(Constants.GET_FOOD_URL + pageNo);
					System.out.println("----------------" + s);
					s = getCacheData(Constants.GET_FOOD_URL + pageNo) ;
					defaul_action = Constants.LISTVIEW_ACTION_FIRST ;
					map = ParseGson.parseFood(s);
					status = (Integer) map.get("status");
					if (status == Constants.LISTVIEW_ACTION_GET_ERROR) {
						message.what = Constants.LISTVIEW_ACTION_GET_ERROR;
					} else if (status == 1) {
						if(!ConfigCache.isExitCacheFile(Constants.GET_FOOD_URL + pageNo)){
							ConfigCache.setUrlCache(s, Constants.GET_FOOD_URL + pageNo) ;
						}
						message.obj = map;
						message.what = Constants.LISTVIEW_ACTION_FIRST;
					}

					break;
				case Constants.LISTVIEW_ACTION_SCROLL:
					// s = HttpUtil.httpGet(Constants.GET_FOOD_URL+pageNo) ;
					// map = ParseGson.parseFood(s) ;
					// status = (Integer) map.get("status") ;
					defaul_action = Constants.LISTVIEW_ACTION_SCROLL ;
					s = HttpUtil.httpGet(Constants.GET_FOOD_URL+pageNo) ;
					map = ParseGson.parseFood(s) ;
					status = (Integer) map.get("status") ;
				//	status = 0;
					switch (status) {
					case 1:
						message.obj = map;
						message.what = Constants.LISTVIEW_ACTION_SCROLL;
						break;
					case 0:
						 message.obj = map ;
						message.what = Constants.LISTVIEW_ACTION_SCROLL;
						break;
					case Constants.LISTVIEW_ACTION_GET_ERROR:
						message.what = Constants.LISTVIEW_ACTION_GET_ERROR;
						break;
					}
					break;
				default:
					break;
				}
				handler.sendMessage(message);
			}
		}).start();

	}

	@Override
	public void onRefresh() {
		// TODO Auto-generated method stub
		listView.stopRefresh();
	}

	@Override
	public void onLoadMore() {
		// TODO Auto-generated method stub
		/*int pageIndex = count / Constants.PAGE_SIZE + 1;
		loadData(Constants.LISTVIEW_ACTION_SCROLL, handler, pageIndex);*/
	
			// int pageIndex = count / Constants.PAGE_SIZE + 1;
			int pageIndex = count % Constants.PAGE_SIZE == 0 ? count
					/ Constants.PAGE_SIZE + 1 : count / Constants.PAGE_SIZE + 2;
			loadData(Constants.LISTVIEW_ACTION_SCROLL, handler, pageIndex);
		
	}
	
	/** 
	* @param url
	* @return  
	* @retur  String 
	* @Description: 获取缓存数据 
	*/
	public String getCacheData(String url){
		String result = null ;
		result = ConfigCache.getUrlCache(url) ;
		if(result == null){
			result = HttpUtil.httpGet(url);
		}
		return result ;
	}

}
